package org.runecore.rs2.io;

import java.util.logging.Logger;

import org.runecore.Launch;
import org.runecore.rs2.model.World;
import org.runecore.rs2.model.mask.UpdateFlag;
import org.runecore.rs2.model.player.GameSession;
import org.runecore.rs2.model.player.Player;
import org.runecore.rs2.net.PacketBuilder;
import org.runecore.rs2.net.StreamBuffer;

/**
 * RuneCore Sep 5, 2011
 * 
 * @author Harry Andreas<Harry@RuneCore.org>
 */
public class PlayerGameManager {

	/**
	 * The <code>Logger</code> instance
	 */
	private final static Logger logger = Launch.getEnv().getLogger();

	/**
	 * Responce codes for login
	 */
	private static final int RESPONCE_OK = 2;
	@SuppressWarnings("unused")
	private static final int RESPONCE_INVALID = 3;
	@SuppressWarnings("unused")
	private static final int RESPONCE_DISABLED = 4;
	private static final int RESPONCE_ONLINE = 5;
	private static final int RESPONCE_WORLD_FULL = 7;

	/**
	 * Handle's a login request
	 * 
	 * @param username
	 * @param password
	 */
	public static Runnable handleLogin(final GameSession session,
			final int UID, final String USER, final String PASS) {
		return new Runnable() {
			@Override
			public void run() {
				getLogger().info(
						"UID: " + UID + " USER: " + USER + " PASS: " + PASS);
				int responce = RESPONCE_OK;
				Object pl = Launch.getEnv().getAccountManager().load(USER);
				Player player = null;
				if(pl == null) {
					player = new Player(USER, PASS, session);
					try {
						Launch.getEnv().getAccountManager().save(player);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					player = (Player)pl;
					player.setSession(session);
				}
				if (World.getSingleton().userOnline(USER)) {
					responce = RESPONCE_ONLINE;
				}
				if(World.getSingleton().getWorldPlayers().size() >= 2000) {
					responce = RESPONCE_WORLD_FULL;
				}
				StreamBuffer.OutBuffer resp = StreamBuffer.newOutBuffer(3);
				resp.writeByte(responce);
				resp.writeByte(2); // rights
				resp.writeByte(0);
				session.sendPacket(resp.getBuffer());
				if (responce != 2) {
					session.exit();
					return;
				}
				session.setPlayer(player);
				World.getSingleton().register(session.getPlayer());
				player.setupEntity();
				player.getEntityMask().flag(UpdateFlag.APPEARANCE);
				PacketBuilder.sendMapRegion(session);
				session.getPlayer().sendSkills();
				PacketBuilder.sendTabs(session);
			}
		};
	}

	/**
	 * @return the logger
	 */
	public static Logger getLogger() {
		return logger;
	}

}
